package com.parleys.android.client.io;

import java.util.ArrayList;
import java.util.HashSet;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentResolver;
import android.util.Log;

import com.parleys.android.client.provider.ParleysContract;
import com.parleys.android.client.provider.ParleysContract.Channels;
import com.parleys.android.client.provider.ParleysContract.Spaces;
import com.parleys.android.client.util.ParleysUriUtils;
import com.parleys.android.client.util.Sets;

public class ChannelsHandler extends JSONHandler {
	
	private static final String TAG = "ChannelsHandler";
	
	public ChannelsHandler() {
		super(ParleysContract.CONTENT_AUTHORITY);
	}

	@Override
	public ArrayList<ContentProviderOperation> parse(JSONArray json, ContentResolver resolver) throws JSONException {
		final ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>();
		final HashSet<Long> channelIds = Sets.newHashSet();
		
		final int jsonSize = json.length();
		for (int i = 0; i < jsonSize; i++) {
			final JSONObject channel = json.getJSONObject(i);
			final long channelId = channel.getLong("id");
			final int spaceId = channel.getInt("spaceId");
			final long createdOn = channel.getLong("createdOn");
			final long modifiedOn = channel.getLong("modifiedOn");
			final String name = channel.getString("name");
			final String description = channel.getString("description");
			final String thumbnailUrl = ParleysUriUtils.removeLeadingSlashes(channel.getString("thumbnailUrl"));
			final boolean isPublic = channel.getBoolean("public");
			final boolean visibleIpad = channel.getBoolean("visibleIpad");
			final boolean iphoneEnabled = channel.getBoolean("iPhoneEnabled");
			final boolean podcastEnabled = channel.getBoolean("podcastEnabled");
			final long totalViewCount = channel.getLong("totalViewCount");
			final boolean subscribed = channel.getBoolean("subscribed");
			
			channelIds.add(channelId);
			
			final ContentProviderOperation.Builder operation = ContentProviderOperation.newInsert(Spaces.buildChannelsDirUri(spaceId));
			operation.withValue(Channels.CHANNEL_ID, channelId)
				.withValue(Channels.CREATED_ON, createdOn)
				.withValue(Channels.MODIFIED_ON, modifiedOn)
				.withValue(Channels.NAME, name)
				.withValue(Channels.DESCRIPTION, description);
			if (thumbnailUrl != null && !isEmptyThumbnail(thumbnailUrl)) {
				operation.withValue(Channels.THUMBNAIL_URL, thumbnailUrl);
			}
			operation.withValue(Channels.PUBLIC, isPublic)
				.withValue(Channels.VISIBLE_IPAD, visibleIpad)
				.withValue(Channels.IPHONE_ENABLED, iphoneEnabled)
				.withValue(Channels.PODCAST_ENABLED, podcastEnabled)
				.withValue(Channels.TOTAL_VIEWCOUNT, totalViewCount)
				.withValue(Channels.SUBSCRIBED, subscribed);
			batch.add(operation.build());
		}

//    	HashSet<Long> lostChannelIds = getLostIds(channelIds, Channels.CONTENT_URI, ChannelsQuery.PROJECTION, ChannelsQuery.CHANNEL_ID, resolver);
//    	for (Iterator<Long> it = lostChannelIds.iterator(); it.hasNext(); ) {
//    		Long lostChannelId = it.next();
//	    	Uri deleteUri = Channels.buildChannelUri(lostChannelId.intValue());
//	    	batch.add(ContentProviderOperation.newDelete(deleteUri).build());
//    	}
		
		return batch;
	}

	@Override
	public void notify(ContentProviderResult[] result, ContentResolver resolver) throws JSONException {
		if (result != null && result.length > 0) {
			Log.d(TAG, "Notifying data set changes for " + result[0].uri);
			resolver.notifyChange(result[0].uri, null);
		}
	}

    private interface ChannelsQuery {
        String[] PROJECTION = {
                Channels.CHANNEL_ID,
        };

        int CHANNEL_ID = 0;
    }

}
